package com.fayuan.nocv.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fayuan.nocv.entity.NocvNews;
import com.fayuan.nocv.service.NocvNewsService;
import com.fayuan.nocv.vo.DataView;
import com.fayuan.nocv.vo.NocvNewsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("/news")
public class NocvNewsController {

    @Autowired
    private NocvNewsService nocvNewsService;

    @GetMapping("/listNews")
    @ResponseBody
    public DataView listNews(NocvNewsVo nocvNewsVo){

        QueryWrapper<NocvNews>wrapper = new QueryWrapper<>();
        if (nocvNewsVo.getTitle()!=null){
            wrapper.like("title",nocvNewsVo.getTitle());
        }

        IPage<NocvNews>page = new Page<>(nocvNewsVo.getPage(),nocvNewsVo.getLimit());
        IPage<NocvNews> page1 = nocvNewsService.page(page, wrapper);
        return new DataView(page1.getTotal(),page1.getRecords());
    }

    @PostMapping("/save")
    @ResponseBody
    public DataView addNews(@RequestBody NocvNews nocvNews){
        nocvNews.setCreateTime(new Date());
        nocvNewsService.save(nocvNews);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("添加新闻成功");
        return dataView;
    }

    @PostMapping("/deleteById")
    @ResponseBody
    public DataView DeleteNews(NocvNews nocvNews){

        nocvNewsService.removeById(nocvNews.getId());
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除新闻成功");
        return dataView;
    }

    @PostMapping("/Update")
    @ResponseBody
    public DataView UpdateNews(NocvNews nocvNews){

        nocvNewsService.updateById(nocvNews);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("修改新闻成功");
        return dataView;
    }
}
